Macro is more powerful, but more dangerous
Powerful in that macro that take substitute the constant values like the const can do,
moreover, it can also take substitute of the expression, or even the code of function.
The macro code will be preprocessed in the pre-process step of the C compiler, which can save the CPU resources.
Moreover, the macro can improve the readability of the code by giving the easy understand name to the specific code.
But the disadvantage also lies in its mechanism of substitution. The compiler will not perform the check of the data type which give a high possibility of potential errors, and such kinds of errors are difficult to be found.
How to organize the headfiles.
Reference link(Ch) http://blog.chinaunix.net/u2/75758/showart_1715158.html
The use of macros
Reference link(Ch) http://blog.21ic.com/user1/69/archives/2006/13695.html
Error prevent of macros definition
1. use ():e.g. #define SUM(a, b) (a+b)
2. use do{}while(0) to include multiple statement
#define M(a, b) do{ a+b; \
a++;}while(0)
use of "#" and "##"
use # to transform the parameter of a macro to string with " "
e.g. #define STR(s) #sprintf(STR(test)); // output is string "test"
e.g. #define dprintf(expr) printf(#expr " = %g\n", expr)
dprint(x/y); ------> printf("x/y = %g\n", x/y);
use "##" to connect two parameters together.
e.g. #define paste(front, back) front##backpaste(name, 1) -------------->name1
e.g. #define CONS(a, b) int(a##e##b)
printf("%d\n", CONS(2,3)) ------------> 2000
typedef &define
typedefは型定義、defineはマクロ定義, Compilerからめれば、作用が同じ。違う点は字面の通り、ユーザがTypedefを見ると、新しい型の定義が分かる、
その以外の場合にdefineを使ったほうが良い
extern &static
macro & const
Macro is more powerful, but more dangerousPowerful in that macro that take substitute the constant values like the const can do,
moreover, it can also take substitute of the expression, or even the code of function.
The macro code will be preprocessed in the pre-process step of the C compiler, which can save the CPU resources.
Moreover, the macro can improve the readability of the code by giving the easy understand name to the specific code.
But the disadvantage also lies in its mechanism of substitution. The compiler will not perform the check of the data type which give a high possibility of potential errors, and such kinds of errors are difficult to be found.
Reference
(JP) http://www.geocities.jp/ky_webid/c/
A tutorial on C language
Inline function & parametrized macro
Compiler will insert the complete body of the inline function at every place it is called.In C, it is implemented by parametrized macro.
No space should be put after backslash"\", otherwise, error will occurs.
The following paper make a good summary on the preprocessor of C
Assert
Assert Assert